const path = require('path')
const webpack = require('webpack')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const autoprefixer = require('autoprefixer')
const CompressionPlugin = require('compression-webpack-plugin')
// const OpenBrowserPlugin = require('open-browser-webpack-plugin')

// 判断当前运行环境是开发模式还是生产模式
const nodeEnv = process.env.NODE_ENV || 'development'
console.log(process.env.NODE_ENV)
const isPro = nodeEnv === 'production'

console.log('当前运行环境：', isPro ? 'production' : 'development')

var plugins = [
  new ExtractTextPlugin('app.css'),
    // new webpack.optimize.ModuleConcatenationPlugin(),
  new webpack.optimize.CommonsChunkPlugin({
    name: 'vendor',
    filename: 'vendor.js'
  }),
  new webpack.DefinePlugin({
        // 定义全局变量
    'process.env': {
      'NODE_ENV': JSON.stringify(nodeEnv)
    }
  })
  // new OpenBrowserPlugin({ url: 'http://localhost:8080' })
]
var app = [
  './entry'
]
if (isPro) {
  plugins.push(
      new webpack.LoaderOptionsPlugin({
        minimize: true,
        debug: false
      }),
      new webpack.optimize.UglifyJsPlugin({
        sourceMap: false,
        comments: false,
        warnings: false
      }),
      new CompressionPlugin({
        asset: '[path].gz[query]',
        algorithm: 'gzip',
        test: /\.js$|\.css$|\.html$|\.eot?.+$|\.ttf?.+$|\.woff?.+$|\.svg?.+$/,
        threshold: 10,
        minRatio: 0.8
      })
  )
} else {
  app.unshift('react-hot-loader/patch', 'webpack-dev-server/client? http://localhost:8080',
  'webpack/hot/only-dev-server')
  plugins.push(
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NamedModulesPlugin(),
        new webpack.NoEmitOnErrorsPlugin()
  )
}

const postcssOpts = {
  ident: 'postcss', // https://webpack.js.org/guides/migrating/#complex-options
  plugins: () => [
    autoprefixer({
      browsers: ['last 2 versions', 'Firefox ESR', '> 1%', 'ie >= 8', 'iOS >= 8', 'Android >= 4']
    })
  ]
}

module.exports = {
  context: path.resolve(__dirname, 'src'),
  devtool: 'source-map',
  entry: {
    app: app,
    vendor: ['react',
      'react-dom',
      'localforage',
      'lrz',
      'mobx',
      'mobx-react',
      'react-router-dom',
      'uxcore'
    ] // 提取react模块作为公共的js文件
  },
  output: {
    filename: '[name].js',
    chunkFilename: '[id].chunk.js',
    path: path.join(__dirname, 'build/src'),
    publicPath: isPro ? '/src/' : '/build/'
  },
    // BASE_URL是全局的api接口访问地址
  plugins,
    // alias是配置全局的路径入口名称，只要涉及到下面配置的文件路径，可以直接用定义的单个字母表示整个路径
  resolve: {
    mainFiles: ['index.web', 'index'],
    extensions: ['.js', '.jsx', '.less', '.scss', '.css', '.web.js'],
    modules: [
      path.resolve(__dirname, 'node_modules'),
      path.join(__dirname, './src')
    ],
    alias: {
      'components': path.resolve(__dirname, 'src/components'),
      'containers': path.resolve(__dirname, 'src/containers'),
      'lib': path.resolve(__dirname, 'src/lib'),
      'images': path.resolve(__dirname, 'src/images'),
      'cvm': path.resolve(__dirname, 'src/cvm')
    }
  },

  module: {
    noParse: /node_modules\/localforage\/dist\/localforage.js/,
    rules: [{
      test: /\.jsx|js$/,
      exclude: /node_modules/,
      loader: 'babel-loader',
      options: {
        plugins: [
          'external-helpers',
          ['transform-runtime', { polyfill: false }],
          'transform-decorators-legacy',
          'syntax-decorators',
          'transform-async-to-generator',
          'transform-do-expressions',
          'syntax-do-expressions'
        ],
        presets: ['es2015', 'stage-2', 'react']
      }
    }, {
      test: /\.less$/i,
      use: ExtractTextPlugin.extract({
        fallback: 'style-loader',
        use: [
          'css-loader', { loader: 'postcss-loader', options: postcssOpts }, 'less-loader'
        ]
      })
    }, {
      test: /\.scss$/i,
      use: ExtractTextPlugin.extract({
        fallback: 'style-loader',
        use: [
          'css-loader', { loader: 'postcss-loader', options: postcssOpts }, 'sass-loader'
        ]
      })
    }, {
      test: /\.css$/i,
      use: ExtractTextPlugin.extract({
        fallback: 'style-loader',
        use: [
          'css-loader', { loader: 'postcss-loader', options: postcssOpts }
        ]
      })
    }, {
      test: /\.(png|jpg|gif|eot|ttf|woff|woff2)$/,
      use: ['url-loader?limit=8192&name=files/[md5:hash:base64:10].[ext]']
    }, {
      test: /\.svg/,
      loader: 'svg-url-loader'
    }]
  },
  devServer: {
    hot: true,
    compress: true,
    port: 8080,
    historyApiFallback: true,
    disableHostCheck: true,
    contentBase: path.resolve(__dirname),
    publicPath: '/build/',
    stats: {
      modules: false,
      chunks: false
    }
  }
}
